import React, { useEffect, useState } from "react";
import { Form, Input, Button } from "antd-mobile";
import { Space, Toast } from "antd-mobile";
import axios from "../../utils/request";
import { useNavigate } from "react-router-dom";
import useFdou from "../../hooks/useFdou";

// import { gettel } from "../../api/index";
function Login() {

  // console.log(gettel)
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 按钮禁用
  const [fs,setFs] = useState(false)

  // 获取登录所需的手机号和验证码
  const onFinish = async (values) => {
    // console.log(values);
    // console.log('11111111111111111111111111111')
    const res = await axios.post("/login/tel", values);
    console.log(res);
    if (res.data.code == 200) {
      const token = res.data.data.token;
      localStorage.setItem("token", token);
      navigate(-1);
      Toast.show({
        icon: "success",
        content: "登录成功",
      });
    } else {
      Toast.show({
        icon: "fail",
        content: "登录失败",
      });
    }
  };

  const [sj, setSj] = useState(60);
  const [as, setAs] = useState(false);
  // 获取验证码
  const gettels =  async() => {
    setAs(true);
    const tel = form.getFieldValue("tel");
    // console.log(tel)
    const timer = setInterval(() => {
      setSj((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          setAs(false);
          setSj(60);
        }
        return prev - 1;
      });
    }, 1000);

    const res = await axios.get("/login/code", { params: { tel } });
    console.log(res)
    const code = res.data.data;
    form.setFieldValue("telCode", code);
    setFs('')
  };

  // useEffect(()=>{
  //   gettels()
  // },[])
  return (
    <div>
      <Form
        form={form}
        onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large" disabled={`${fs}`}>
            提交
          </Button>
        }
      >
        <Form.Item
          name="tel"
          label="手机号"
          rules={[
            { required: true, message: "不能为空" },
            { pattern: /^1[3-9]\d{9}$/, message: "请输入手机号" },
          ]}
        >
          <Input o placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="telCode"
          label="短信验证码"
          rules={[{ required: true, message: "不能为空" }]}
          extra={
            <Button
              onClick={() => {
                gettels();
              }}
            >
              {as ? `${sj}秒后重新获取` : "获取验证码"}
            </Button>
          }
        >
          <Input />
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
